package com.ylbh.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @program: ImgDemo
 * @description:
 * @author: Zhuozhuang.Lv
 * @create: 2019-12-06 20:44
 */

public class Grip {

    private final Logger log = LoggerFactory.getLogger(Grip.class);

    public static void main(String[] args) throws Throwable {

        //批量
//        File fileByUrl = getFileByUrl("https://du.hupucdn.com/FlyWbf5CVPLRropEWYbVH12kUGWs?imageView2/2/w/960", "jpg");
//        new Grip().createNewPic(fileByUrl, "/Users/chenchenchaoxiong/Downloads/ImgDemo/src/main/resources/default.png", "");
//        System.out.println(fileByUrl);
//        fileByUrl.delete();
        //批量
//        new Grip().createNewPics("D:\\cache", "D:\\default.png", "D:\\cache\\demo\\");

    }


    /**
     * @param f 需要【处理的图片】
     * @param targetPicPath 设置【处理过的图片】的存放文件夹
     * @throws IOException
     */
    public  void createNewPic(File f, String targetPicPath, Integer type) throws IOException {
        createNewPic(f,null,targetPicPath, type);
    }


    /**
     *
     * @param f 需要【处理的图片】
     * @param backGroundPicPath 底图【一张空白图】
     * @param targetPicPath 设置【处理过的图片】的存放文件夹
     * @throws IOException
     */
    public String createNewPic(File f, String backGroundPicPath, String targetPicPath, Integer type) throws IOException {
        if (f.isFile()) {
            if (isPic(f)) {
                Image img = null;
                if (StringUtils.isEmpty(backGroundPicPath)) {
                    URL imgUrl = this.getClass().getClassLoader().getResource("static/default.png");
                    img = Toolkit.getDefaultToolkit().getImage(imgUrl);
                } else {
//                    File file = new File(this.getClass().getClassLoader().getResource("static/default.png").getPath());
                    File file = getFileByUrl("https://image.yilianbaihui.cn/consumer/upload/store/33307/2019/12/14/1576306894811.png", "png");
                    img = ImageIO.read(file);
//                    InputStream inputStream = this.getClass().getResourceAsStream("/static/default.png");
//                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
//                    img = new BufferedReader(inputStreamReader);
                }

                if (StringUtils.isEmpty(img)) {
                    return "图片上传失败";
                }

                //开始
                int width = 0;
                int height = 0;
                if (type == 0) {
                    width = (int) ((int) img.getWidth(null) / 1.03);
                    height = (int) ((int) img.getHeight(null) / 1.03);
                } else if (type == 1){
                    width = (int) ((int) img.getWidth(null) / 1.55);
                    height = (int) ((int) img.getHeight(null) / 1.55);
                } else if (type == 2){
                    width = (int) ((int) img.getWidth(null) * 3.9);
                    height = (int) ((int) img.getHeight(null) * 3.9);
                } else if (type == 3){
                    width = (int) ((int) img.getWidth(null) * 1.2);
                    height = (int) ((int) img.getHeight(null) * 1.2);
                }else if (type == 4){
                    width = (int) ((int) img.getWidth(null) * 0.8);
                    height = (int) ((int) img.getHeight(null) * 0.8);
                } else if (type == 5){
                    width = (int) ((int) img.getWidth(null) * 1.7);
                    height = (int) ((int) img.getHeight(null) * 1.7);
                } else if (type == 6){
                    width = (int) ((int) img.getWidth(null) * 0.5);
                    height = (int) ((int) img.getHeight(null) * 0.5);
                }
                //create target image
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//get a graphics pen
                Graphics g = image.createGraphics();//draw source image
                g.drawImage(img, 0, 0, width, height, null);
                //draw target logo
                BufferedImage doPic = ImageIO.read(f);
                if (doPic.getWidth() > width || doPic.getHeight() > height) {
                    BufferedImage didPic = resize(doPic, width, height);
                }
                BufferedImage didPic = doPic;
                int lw = didPic.getWidth(null);
                int lh = didPic.getHeight(null);
                int px_x = (width - lw) / 2;
                int px_y = (height - lh) / 2;
                g.drawImage(didPic, px_x, px_y, lw, lh, null);
                //这里是添加水印文字//				 String str = "http://www.hongliang.net";
//				 g.setColor(Color.red);
//				 g.setFont(new Font("Courier", Font.PLAIN, 36));
                //水印文字对准//			    g.drawString(str, width-400, height-60);
                g.dispose();
                FileOutputStream os = new FileOutputStream(targetPicPath + f.getName());
                String formatName = f.getName().substring(f.getName().lastIndexOf(".") + 1);
                //FileOutputStream out = new FileOutputStream(dstName);
                //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                //encoder.encode(dstImage);
                ImageIO.write(image, /*"GIF"*/ formatName /* format desired */ , new File(f.getName()) /* target */ );
//                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//                encoder.encode(image);
                OSSClient os1 = new OSSClient();

                File file2 = new File(f.getName());
                InputStream inputStream = new FileInputStream(file2);
                String time = "33307/"+DateHelper.getDate();
                String s1 = os1.uploadFile2OSS(inputStream, "consumer/upload/store/", ".jpg", time);
                file2.delete();
                if ("fail".equals(s1)) {
                    return "图片上传失败";
                }
                os.close();
                System.out.println("s1的time"+ time + "===" + s1);
                return "upload/store/" + time + "/" + s1;
            }
        }
        return "图片上传失败";
    }


    /**
     *
     * @param dir 需要【处理图片】的所在文件夹
     * @param backGroundPicPath 底图【一张空白图】
     * @param targetPicPath 设置【处理过的图片】的存放文件夹
     * @throws IOException
     */
    public  void createNewPics(String dir, String backGroundPicPath, String targetPicPath, Integer type) throws IOException {

        File ML = new File(dir);
        File[] files = ML.listFiles();

        for (File f : files) {
            createNewPic(f, backGroundPicPath, targetPicPath, type);
        }
    }

    /**
     * @param dir 需要【处理图片】的所在文件夹
     * @param targetPicPath 设置【处理过的图片】的存放文件夹
     * @throws IOException
     */
    public  void createNewPics(String dir, String targetPicPath, Integer type) throws IOException {
        createNewPics(dir, null, targetPicPath, type);
    }


    public  BufferedImage resize(BufferedImage source, int targetW, int targetH) {
        // targetW，targetH分别表示目标长和宽
        int type = source.getType();
        BufferedImage target = null;
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        //这里想实现在targetW，targetH范围内实现等比缩放。如果不需要等比缩放
        //则将下面的if else语句注释即可
        if (sx > sy) {
            sx = sy;
            targetW = (int) (sx * source.getWidth());
        } else {
            sy = sx;
            targetH = (int) (sy * source.getHeight());
        }
        if (type == BufferedImage.TYPE_CUSTOM) { //handmade
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else {
            target = new BufferedImage(targetW, targetH, type);
        }
        Graphics2D g = target.createGraphics();
        //smoother than exlax:
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }

    public  boolean isPic(File file) {
        String imgeArray[] = {"bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};
        String fileName = file.getName();
        fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
        for (String suffix : imgeArray) {
            if (fileName.equals(suffix)) {
                return true;
            }
        }
        return false;
    }

    public static File getFileByUrl(String fileUrl, String suffix) {

        ByteArrayOutputStream outStream =new ByteArrayOutputStream();

        BufferedOutputStream stream =null;

        InputStream inputStream =null;

        File file =null;

        try {

            URL imageUrl =new URL(fileUrl);

            HttpURLConnection conn =(HttpURLConnection)imageUrl.openConnection();

            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            inputStream = conn.getInputStream();

            byte[] buffer =new byte[1024];

            int len =0;

            while( (len=inputStream.read(buffer)) != -1 ){

                outStream.write(buffer, 0, len);

            }

            file = File.createTempFile("pattern", "." + suffix);

            System.out.println("临时文件创建成功={}" + file.getCanonicalPath());

            FileOutputStream fileOutputStream =new FileOutputStream(file);

            stream =new BufferedOutputStream(fileOutputStream);

            stream.write(outStream.toByteArray());

        } catch (Exception e) {

            System.out.println("创建人脸获取服务器图片异常" + e);

        } finally {

            try {

                if (inputStream !=null) inputStream.close();

                if (stream !=null) stream.close();

                outStream.close();

            } catch (Exception e) {
                System.out.println("关闭流异常" + e);}

        }
        return file;
    }
}
